<template>
  <div class="p-6">
    <h1 class="text-2xl font-bold mb-6">设置</h1>
    
    <div class="bg-white p-4 rounded-lg">
      <h2 class="text-lg font-medium mb-4">OpenAI 配置</h2>
      <a-form :model="settings" layout="vertical">
        <a-form-item 
          label="API Key" 
          :validate-status="apiKeyStatus"
          :help="apiKeyMessage"
        >
          <a-input-password
            v-model="settings.openAIKey"
            placeholder="请输入 OpenAI API Key"
            allow-clear
            @change="handleApiKeyChange"
          />
        </a-form-item>
        
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="saveSettings" :loading="saving">
              保存设置
            </a-button>
            <a-button @click="testConnection" :loading="testing">
              测试连接
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useAppStore } from '../store'
import { Message } from '@arco-design/web-vue'
import type { AppSettings } from '@/types'
import { validateAPIKey, initOpenAIClient } from '@/config/openai'

const store = useAppStore()
const settings = ref<AppSettings>({ ...store.settings })
const saving = ref(false)
const testing = ref(false)
const apiKeyStatus = ref<'' | 'error' | 'success'>('')
const apiKeyMessage = ref('')

// 处理 API Key 变化
const handleApiKeyChange = () => {
  apiKeyStatus.value = ''
  apiKeyMessage.value = ''
}

// 测试连接
const testConnection = async () => {
  if (!settings.value.openAIKey) {
    apiKeyStatus.value = 'error'
    apiKeyMessage.value = '请输入 API Key'
    return
  }

  testing.value = true
  try {
    const isValid = await validateAPIKey(settings.value.openAIKey)
    if (isValid) {
      apiKeyStatus.value = 'success'
      apiKeyMessage.value = '连接成功'
      Message.success('API Key 验证成功')
    } else {
      apiKeyStatus.value = 'error'
      apiKeyMessage.value = 'API Key 无效'
      Message.error('API Key 验证失败')
    }
  } catch (error) {
    apiKeyStatus.value = 'error'
    apiKeyMessage.value = '连接失败'
    Message.error('连接测试失败')
  } finally {
    testing.value = false
  }
}

// 保存设置
const saveSettings = async () => {
  if (!settings.value.openAIKey) {
    apiKeyStatus.value = 'error'
    apiKeyMessage.value = '请输入 API Key'
    return
  }

  saving.value = true
  try {
    // 验证 API Key
    const isValid = await validateAPIKey(settings.value.openAIKey)
    if (!isValid) {
      apiKeyStatus.value = 'error'
      apiKeyMessage.value = 'API Key 无效'
      Message.error('API Key 无效，请检查后重试')
      return
    }

    // 初始化 OpenAI 客户端
    const initialized = initOpenAIClient(settings.value.openAIKey)
    if (!initialized) {
      throw new Error('初始化 OpenAI 客户端失败')
    }

    // 保存设置
    store.updateSettings(settings.value)
    Message.success('设置保存成功')
    apiKeyStatus.value = 'success'
  } catch (error) {
    Message.error('设置保存失败')
    console.error('保存设置失败:', error)
  } finally {
    saving.value = false
  }
}
</script> 